<?php

class UsersController extends AppController
{

    var $name = 'Users';

    function beforeFilter()
    {
        parent::beforeFilter();

        if( ($this->params['action'] == 'delete') && ($this->Session->read('Auth.Employee.id') != Configure::read('employeetype.admin.id')) )
        {
            $this->Session->setFlash(__('You are not allowed to delete', true), 'notice');
            $this->redirect(array('controller' => 'users', 'action' => 'index'));
        }
    }

    function index()
    {
        if( $this->RequestHandler->isAjax() )
        {
            //pr($this->params);
            $this->autoRender = false;

            // get how many rows we want to have into the grid - rowNum parameter in the grid
            $limit = $this->params['url']['rows'];

            // get index row - i.e. user click to sort. At first time sortname parameter -
            // after that the index from colModel
            $sidx = $this->params['url']['sidx'];

            // sorting order - at first time sortorder
            $sord = $this->params['url']['sord'];

            $page = $this->params['url']['page'];

            // if we not pass at first time index use the first column for the index or what you want
            if( !$sidx ) $sidx = 1;

            // calculate the number of rows for the query. We need this for paging the result
            $row = $this->User->find('count');
            $count = $row;

            // calculate the total pages for the query
            if( $count > 0 )
            {
                $total_pages = ceil($count / $limit);
            }
            else
            {
                $total_pages = 0;
            }

            // if for some reasons the requested page is greater than the total
            // set the requested page to total page
            if( $page > $total_pages ) $page = $total_pages;

            // calculate the starting position of the rows
            $start = $limit * $page - $limit;

            // if for some reasons start position is negative set it to 0
            // typical case is that the user type 0 for the requested page
            if( $start < 0 ) $start = 0;

            // the actual query for the grid data
            $limit_range = $start . "," . $limit;
            $sort_range = $this->modelClass . "." . $sidx . " " . $sord;

            if( $this->params['url']['_search'] == 'true' )
            {
                $searchconditions = array();

                if( isset($this->params['url']['firstname']) && !empty($this->params['url']['firstname']) )
                {
                    array_push(&$searchconditions, array('User.firstname LIKE' => $this->params['url']['firstname'] . '%'));
                }
                if( isset($this->params['url']['lastname']) && !empty($this->params['url']['lastname']) )
                {
                    array_push(&$searchconditions, array('User.lastname LIKE' => $this->params['url']['lastname'] . '%'));
                }
                if( isset($this->params['url']['email1']) && !empty($this->params['url']['email1']) )
                {
                    array_push(&$searchconditions, array('User.email1 LIKE' => $this->params['url']['email1'] . '%'));
                }
                if( isset($this->params['url']['city']) && !empty($this->params['url']['city']) )
                {
                    array_push(&$searchconditions, array('City.name LIKE' => $this->params['url']['city'] . '%'));
                }
                if( isset($this->params['url']['mobilephone']) && !empty($this->params['url']['mobilephone']) )
                {
                    array_push(&$searchconditions, array('User.mobilephone LIKE' => $this->params['url']['mobilephone'] . '%'));
                }

                $result = $this->User->find('all', array(
                    'fields' => array('id', 'firstname', 'lastname', 'mobilephone', 'email1', 'city_id'),
                    'conditions' => $searchconditions,
                    'link' => array(
                        'City' => array(
                            'fields' => array('id', 'name')
                        )
                    ),
                    'order' => $sort_range,
                    'limit' => $limit_range
                ));
            }
            else
            {
                $result = $this->User->find('all', array(
                    'contain' => array(
                        'City' => array(
                            'fields' => array('id', 'name')
                        )
                    ),
                    'order' => $sort_range,
                    'limit' => $limit_range
                ));
            }

            $i = 0;
            $response->page = $page;
            $response->total = $total_pages;
            $response->records = $count;

            foreach($result as $result)
            {
                $response->rows[$i]['id'] = $result['User']['id'];

                $firstname = "<a href='" . APP_URL . "users/view/" . $result['User']['id'] . "'>" . $result['User']['firstname'] . "</a>";
                $lastname = "<a href='" . APP_URL . "users/view/" . $result['User']['id'] . "'>" . $result['User']['lastname'] . "</a>";
                $email = $result['User']['email1'];
                $mobile = $result['User']['mobilephone'];
                $city = $result['City']['name'];
                $addactivity = "<a class='linkbutton' title='new activity' href='" . APP_URL . "useractivities/add/foruser:" . $result['User']['id'] . "'><img src=" . APP_URL . "img/new_activity.gif /></a>";
                $sendemail = "<a class='linkbutton' title='send email' href='" . APP_URL . "useractivities/email/" . $result['User']['id'] . "'><img src=" . APP_URL . "img/email.png /></a>";
                $convert = "<a class='linkbutton' title='convert to potential' href='" . APP_URL . "potentials/add/" . $result['User']['id'] . "'><img src=" . APP_URL . "img/convert.gif /></a>";
                $view = "<a class='linkbutton' title='view' href='" . APP_URL . "users/view/" . $result['User']['id'] . "'><img src=" . APP_URL . "img/view.png /></a>";
                $edit = "<a class='linkbutton' title='edit' href='" . APP_URL . "users/edit/" . $result['User']['id'] . "'><img src=" . APP_URL . "img/edit.png /></a>";
                $delete = "<a class='linkbutton' title='delete' href=\"#\" onclick=\"if(confirm('Are you sure you want to delete this ?')){window.location.href= '" . APP_URL . "admin/users/delete/" . $result['User']['id'] . "'}\"><img src=" . APP_URL . "img/delete.png /></a>";
                if( $this->Session->read('Auth.Employee.employeetype_id') == Configure::read('employeetype.admin.id') )
                {
                    $actions = $addactivity . $sendemail . $convert . $view . $edit . $delete;
                }
                else
                {
                    $actions = $addactivity . $sendemail . $convert . $view . $edit;
                }

                $response->rows[$i]['cell'] = array($firstname, $lastname, $email, $mobile, $city, $actions);
                $i++;
            }

            echo json_encode($response);
            //exit;
        }
    }

    function view($id = null)
    {
        if( !$id )
        {
            $this->Session->setFlash(__('Invalid user', true));
            $this->redirect(array('action' => 'index'));
        }
        $user = $this->User->find('first', array(
            'conditions' => array(
                'User.id' => $id
            ),
            'contain' => array(
                'Potential' => array(
                    'Product' => array(
                        'fields' => array('id', 'name')
                    ),
                    'Leadstage' => array(
                        'fields' => array('id', 'name')
                    ),
                    'Dealstage' => array(
                        'fields' => array('id', 'name')
                    ),
                    'Employee' => array(
                        'fields' => array('id', 'firstname', 'lastname')
                    ),
                    'Assignedtoemployee' => array(
                        'fields' => array('id', 'firstname', 'lastname')
                    ),
                    'Location' => array(
                        'fields' => array('id', 'name')
                    )
                ),
                'Location' => array(
                    'fields' => array('id', 'name')
                ),
                'Employee' => array(
                    'fields' => array('id', 'firstname', 'lastname')
                ),
                'City' => array(
                    'fields' => array('id', 'name')
                ),
                'Leadsource' => array(
                    'fields' => array('id', 'name')
                ),
                'Awarenesssource' => array(
                    'fields' => array('id', 'name')
                )
            )
        ));
        $this->set('user', $user);
    }

    function add()
    {
        $this->_addUser();
    }

    function edit($id = null)
    {
        $this->_editUser($id);
    }

    function delete($id = null)
    {
        $this->_deleteUser($id);
    }

    function uploadcsv()
    {
        $this->autoRender = false;

        if( isset($this->data['User']['csvfile']['tmp_name']) && !empty($this->data['User']['csvfile']['tmp_name']) )
        {
            $destination = ROOT . DS . APP_DIR . DS . "tmp" . DS . $this->data['User']['csvfile']['name'];
            if( strtolower($this->data['User']['csvfile']['type']) == 'text/csv' )
            {
                if( move_uploaded_file($this->data['User']['csvfile']['tmp_name'], $destination) )
                {
                    $row = 1;
                    $count = 0;
                    $failures = 0;
                    $errors = "";
                    if( ($handle = fopen($destination, "r")) !== FALSE )
                    {
                        while(($data = fgetcsv($handle, 1000, ",")) !== FALSE)
                        {
                            $temperr = '0';
                            //remove extra space and convert to lower string for string to match correctly
                            $cityname = ucfirst(strtolower(trim($data[3])));
                            $city = $this->User->City->find('first', array(
                                'fields' => array('id', 'name'),
                                'conditions' => array(
                                    'City.name' => $cityname
                                ),
                                'recursive' => -1
                            ));
                            if( empty($city) )
                            {
                                $errors .= "* Invalid city '" . $cityname . "' on line '" . $row . "' in csv file.<br>";
                                $temperr = true;
                            }

                            $leadsourcename = strtolower(trim($data[7]));
                            $leadsource = $this->User->Leadsource->find('first', array(
                                'fields' => array('id', 'name'),
                                'conditions' => array(
                                    'Leadsource.name' => $leadsourcename
                                ),
                                'recursive' => -1
                            ));
                            if( empty($leadsource) )
                            {
                                $errors .= "* Invalid lead source '" . $cityname . "' on line '" . $row . "' in csv file.<br>";
                                $temperr = '1';
                            }

                            $locationname = strtolower(trim($data[8]));
                            $location = $this->User->Location->find('first', array(
                                'fields' => array('id', 'name'),
                                'conditions' => array(
                                    'Location.name' => $locationname
                                ),
                                'recursive' => -1
                            ));
                            if( empty($location) )
                            {
                                $errors .= "* Invalid location '" . $locationname . "' on line '" . $row . "' in csv file.<br>";
                                $temperr = '1';
                            }

                            $awarenesssourcename = ucfirst(strtolower(trim($data[9])));
                            $awarenesssource = $this->User->Awarenesssource->find('first', array(
                                'fields' => array('id', 'name'),
                                'conditions' => array(
                                    'Awarenesssource.name' => $awarenesssourcename
                                ),
                                'recursive' => -1
                            ));
                            if( empty($awarenesssource) )
                            {
                                $errors .= "* Invalid Awareness source '" . $awarenesssourcename . "' on line '" . $row . "' in csv file.<br>";
                                $temperr = '1';
                            }

                            if( $temperr == '0' )
                            {
                                $count++;
                                $values = array(
                                    'firstname' => Sanitize::clean($data[0], array('remove_html' => true)),
                                    'lastname' => Sanitize::clean($data[1], array('remove_html' => true)),
                                    'address' => Sanitize::clean($data[2], array('remove_html' => true)),
                                    'city_id' => $city['City']['id'],
                                    'pincode' => Sanitize::clean($data[4], array('remove_html' => true)),
                                    'mobilephone' => Sanitize::clean($data[5], array('remove_html' => true)),
                                    'email1' => Sanitize::clean($data[6], array('remove_html' => true)),
                                    'leadsource_id' => $leadsource['Leadsource']['id'],
                                    'location_id' => $location['Location']['id'],
                                    'awarenesssource_id' => $awarenesssource['Awarenesssource']['id'],
                                    'employee_id' => $this->Auth->user('id')
                                );
                                $this->User->create();
                                $this->User->save($values, false);
                            }
                            else
                            {
                                $failures++;
                            }
                            $row++;
                        }
                        fclose($handle);
                    }

                    $this->Session->setFlash(__('The CSV file has been imported successfully.<br>Imported a total of ' . ($count) . ' entries with ' . $failures . ' errors.<br>' . $errors, true), 'info');
                    $this->redirect(array('controller' => 'users', 'action' => 'index'));
                    @unlink($destination);
                }
                else
                {
                    $this->Session->setFlash(__('Your CSV file has not been imported. Please try again.', true), 'notice');
                    $this->redirect(array('controller' => 'users', 'action' => 'index'));
                }
            }
            else
            {
                $this->Session->setFlash(__('Please upload a valid csv file only.', true), 'notice');
                $this->redirect(array('controller' => 'users', 'action' => 'index'));
            }
        }
        else
        {
            $this->Session->setFlash('Please provide a csv file.', 'notice');
            $this->redirect(array('controller' => 'users', 'action' => 'index'));
        }
    }

    function admin_index()
    {
        if( isset($this->params['named']['ajax']) && $this->params['named']['ajax'] == '1' )
        {
            //pr($this->params);
            $this->autoRender = false;

            // get how many rows we want to have into the grid - rowNum parameter in the grid
            $limit = $this->params['url']['rows'];

            // get index row - i.e. user click to sort. At first time sortname parameter -
            // after that the index from colModel
            $sidx = $this->params['url']['sidx'];

            // sorting order - at first time sortorder
            $sord = $this->params['url']['sord'];

            $page = $this->params['url']['page'];

            // if we not pass at first time index use the first column for the index or what you want
            if( !$sidx ) $sidx = 1;

            // calculate the number of rows for the query. We need this for paging the result
            $row = $this->User->find('count');
            $count = $row;

            // calculate the total pages for the query
            if( $count > 0 )
            {
                $total_pages = ceil($count / $limit);
            }
            else
            {
                $total_pages = 0;
            }

            // if for some reasons the requested page is greater than the total
            // set the requested page to total page
            if( $page > $total_pages ) $page = $total_pages;

            // calculate the starting position of the rows
            $start = $limit * $page - $limit;

            // if for some reasons start position is negative set it to 0
            // typical case is that the user type 0 for the requested page
            if( $start < 0 ) $start = 0;

            // the actual query for the grid data
            $limit_range = $start . "," . $limit;
            $sort_range = $sidx . " " . $sord;

            $this->User->recursive = -1;

            if( $this->params['url']['_search'] == 'true' )
            {
                $result = $this->User->find('all', array(
                    'fields' => array('id', 'firstname', 'lastname'),
                    'conditions' => array('User.firstname LIKE' => $this->params['url']['firstname'] . '%'),
                    'order' => $sort_range,
                    'limit' => $limit_range
                ));
            }
            else
            {
                $result = $this->User->find('all', array(
                    'fields' => array('id', 'firstname', 'lastname'),
                    'order' => $sort_range,
                    'limit' => $limit_range
                ));
            }

            $i = 0;
            $response->page = $page;
            $response->total = $total_pages;
            $response->records = $count;

            foreach($result as $result)
            {
                $response->rows[$i]['id'] = $result['User']['id'];

                $firstname = "<a href='" . APP_URL . "admin/users/view/" . $result['User']['id'] . "'>" . $result['User']['firstname'] . "</a>";
                $lastname = "<a href='" . APP_URL . "admin/users/view/" . $result['User']['id'] . "'>" . $result['User']['lastname'] . "</a>";
                $view = "<a title='view' href='" . APP_URL . "admin/users/view/" . $result['User']['id'] . "'>view</a>";
                $edit = "<a title='edit' href='" . APP_URL . "admin/users/edit/" . $result['User']['id'] . "'>edit</a>";
                $delete = "<a title='delete' href=\"#\" onclick=\"if(confirm('Are you sure you want to delete this ?')){window.location.href= '" . APP_URL . "admin/users/delete/" . $result['User']['id'] . "'}\">delete</a>";
                $actions = $view . "    " . $edit . "    " . $delete;

                $response->rows[$i]['cell'] = array($firstname, $lastname, $actions);
                $i++;
            }

            echo json_encode($response);
            //exit;
        }
    }

    function admin_view($id = null)
    {
        if( !$id )
        {
            $this->Session->setFlash(__('Invalid user', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->set('user', $this->User->read(null, $id));
    }

    function admin_add()
    {
        $this->_addUser();
    }

    function admin_edit($id = null)
    {
        $this->_editUser($id);
    }

    function admin_delete($id = null)
    {
        $this->_deleteUser($id);
    }

    function _addUser()
    {
        if( !empty($this->data) )
        {
            $this->User->create();
            if( $this->User->save($this->data) )
            {
                $this->Session->setFlash(__('The user has been added successfully', true), 'success');
                $this->redirect(array('action' => 'index'));
            }
            else
            {
                $this->Session->setFlash(__('The user could not be added. Please, try again.', true), 'notice');
            }
        }
        $states = $this->User->City->State->find('list');
        $leadsources = $this->User->Leadsource->find('list');
        $locations = $this->User->Location->find('list');
        $awarenesssources = $this->User->Awarenesssource->find('list');
        //$employees = $this->User->Employee->find('list');
        $this->set(compact('states', 'leadsources', 'locations', 'awarenesssources'));
    }

    function _editUser($id = null)
    {
        if( !$id && empty($this->data) )
        {
            $this->Session->setFlash(__('Invalid user', true), 'error');
            $this->redirect(array('action' => 'index'));
        }
        if( !empty($this->data) )
        {
            if( $this->User->save($this->data) )
            {
                $this->Session->setFlash(__('The user has been edited successfully', true), 'success');
                $this->redirect(array('action' => 'index'));
            }
            else
            {
                $this->Session->setFlash(__('The user could not be edited. Please, try again.', true), 'notice');
            }
        }
        if( empty($this->data) )
        {
            $this->data = $this->User->find('first', array(
                'conditions' => array('User.id' => $id),
                'contain' => array(
                    'City' => array(
                        'fields' => array('id', 'name'),
                        'State' => array(
                            'fields' => array('id', 'name')
                        )
                    ),
                    'Tag' => array(
                        'fields' => array('id', 'name', 'keyname')
                    )
                )
            ));
        }

        $states = $this->User->City->State->find('list');
        $leadsources = $this->User->Leadsource->find('list');
        $locations = $this->User->Location->find('list');
        $awarenesssources = $this->User->Awarenesssource->find('list');
        $employees = $this->User->Employee->find('list');
        $this->set(compact('states', 'leadsources', 'locations', 'awarenesssources', 'employees', 'userinfo'));
    }

    function _deleteUser($id = null)
    {
        if( !$id )
        {
            $this->Session->setFlash(__('Invalid user', true), 'error');
            $this->redirect(array('action' => 'index'));
        }
        if( $this->User->delete($id) )
        {
            $this->Session->setFlash(__('User deleted', true), 'success');
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('User was not deleted', true), 'notice');
        $this->redirect(array('action' => 'index'));
    }

}

?>